
const express = require('express');;
const app = express();
const user = require('./router/user.js');
const session = require('express-session');
const redisStore = require('connect-redis')(session);
const log4js = require('log4js');
const path = require('path');
const history = require('connect-history-api-fallback');
log4js.configure('./config/log4js.json');
// const bodyparser = require('body-parser');

// app.use(bodyparser.json()); // 使用bodyparder中间件，
// app.use(bodyparser.urlencoded({ extended: true }));
const staticPath = './../dist';
app.use(express.static(path.join(__dirname, staticPath)));

//跨域设置
app.all("*", function (req, res, next) {
    if (req.path !== "/" && !req.path.includes(".")) {
        res.header("Access-Control-Allow-Credentials", true);
        // 这里获取 origin 请求头 而不是用 *
        res.header("Access-Control-Allow-Origin", req.headers["origin"] || "*");
        res.header('Access-Control-Allow-Credentials', 'true')
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
        res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
        res.header("Content-Type", "application/json;charset=utf-8");
    }
    next();
});


//redis模板
// const redis = require("./redis/redis") // 你的redis配置文件路径
// redis.set('sessionId','gyc')  //account为登录帐号信息，需要自行设置

// redis.get('sessionId').then(function (result) {
//     console.log(result)
// })


var sessionConfig = {
    cookie: {
        secure: false,
        maxAge: 1000 * 3600
    },
    sessionStore: {
        host: 'localhost',
        ttl: 3600,
        port: 6379,
        logErrors: true
    }
}

app.use(session({
    secret: "app", // 对session id 相关的cookie 进行签名
    resave: false,
    saveUninitialized: false, // 是否保存未初始化的会话
    store: new redisStore(sessionConfig.sessionStore),
    cookie: sessionConfig.cookie,
    rolling:true,
}))

app.get('/', function (req, res, next) {
    res.send('hello')
})

app.use(log4js.connectLogger(log4js.getLogger("http"), { level: 'auto' }));
app.use('/user', user)
app.use(history());

app.listen(3333, function () {
    console.log('app is listening at port 3333');
});
